export default {
  namespaced: true,
  state: {
    cart: uni.getStorageSync('cart') || []
  },
  mutations: {
    // 加入购物车
    addCart(state, goodsObj) {
      // 判断这件商品有没有在购物车中存在，有的话就直接让数量+1就可以了
      const obj = state.cart.find(item => item.goods_id === goodsObj.goods_id)
      //如果不存在直接添加
      // 存在直接在原来的基础上+1
      if (!obj) {
        state.cart.push(goodsObj)
      } else {
        obj.goods_count += 1
      }
      uni.setStorageSync('cart', state.cart)
      console.log(state.cart)
    },
    // 修改选中状态的值
    setChageRadio(state, goodsObj) {
      const obj = state.cart.find(item => item.goods_id === goodsObj.goods_id)
      if (obj) {
        obj.goods_status = goodsObj.goods_status
      }
      uni.setStorageSync('cart', state.cart)
    },
    // 购物车数量持久化
    ChageCount(state, goodsObj) {
      const obj = state.cart.find(item => item.goods_id === goodsObj.goods_id)
      if (obj) {
        obj.goods_count = goodsObj.goods_count
      }
      uni.setStorageSync('cart', state.cart)
    },
    // 点击删除
    removeCart(state, goods_id) {
      const newCart = state.cart.filter(item => item.goods_id !== +goods_id)
      state.cart = newCart
      uni.setStorageSync('cart', state.cart)
    },
    // 结算的全选和反选
    changeAllStatus(state, bool) {
      state.cart.forEach(item => item.goods_status = bool)
      uni.setStorageSync('cart', state.cart)
    }
  },
  actions: {},
  getters: {
    // 计算购物车的数量
    total(state) {
      // 选中的才把他加都结算数量里面，没有选中直接赋值为0
      return state.cart.reduce((sum, item) => sum += item.goods_status ? item.goods_count : 0, 0)
    },
    // 结算的选中状态
    isCheckAll(state) {
      return state.cart.every(item => item.goods_status)
    },
    // 计算勾选的总价
    total_price(state) {
    return  state.cart.reduce((sum, item) => sum += item.goods_status ? item.goods_count * item.goods_price : 0, 0)
    }
  },
  modules: {}
}
